package servidor.principal.control;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.jdo.Extent;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import servidor.dominio.Categoria;
import servidor.dominio.Cliente;
import servidor.dominio.Concepto;
import servidor.dominio.Empleado;
import servidor.dominio.ReciboDeSueldo;
import servidor.principal.control.*;
import servidor.principal.assembler.*;

import comun.dto.*;
import comun.iControl.*;


public class ControlReciboDeSueldo extends UnicastRemoteObject implements IControlReciboDeSueldo{

	public ControlReciboDeSueldo() throws RemoteException {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public boolean addReciboDeSueldoDTO(ReciboDeSueldoDTO rDTO,String cuitEmpresa,String cat, String cuilEmpleado,Set con)throws Exception{
	PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    PersistenceManager pm = pmf.getPersistenceManager();
    Transaction tx=pm.currentTransaction();
   
    //VER EL MES Y EL CLIENTE CON EL MES NNO ALCANZA
		try{
			 tx.begin();
			 
			    String filter = "cuit == \""+cuitEmpresa+"\""; 
				String filter2= "nombre==\""+cat+"\"";	
				String filter3= "cuil==\""+cuilEmpleado+"\"";


				Cliente cliente = (Cliente)this.getObject(pm, Cliente.class, filter);
				Categoria categoria=(Categoria)this.getObject(pm, Categoria.class, filter2); 
				Empleado empleado=(Empleado)this.getObject(pm, Empleado.class, filter3);
				//conceptos.add(concepto);
				ReciboDeSueldoAssembler recbAssembler = new ReciboDeSueldoAssembler();
				ReciboDeSueldo recb= recbAssembler.getReciboDeSueldo(rDTO);

		//		recb.setEmpresa(cliente); 
				recb.setCategoria(categoria);
				recb.setEmpleado(empleado);
			//	recb.setConceptos(con);
				//Agrego Conceptos
			/*	Set conceptos = new HashSet();
				for(int i =0;i< con.size();i++){
					Concepto concept = (Concepto) con.get(i);

					Concepto concep = new Concepto();
					concep.setEmpleados(empl);
					concep.setImporte(concept.getImporte());
					concep.setPorcentaje(concept.getPorcentaje());
					concep.setRemunerativo(concept.getRemunerativo());
					concep.setTipo(concept.getTipo());
					//setCuitEmpresa(empl.getCuit());
					concep.setDescripcion(concept.getDescripcion());

					//pm.makePersistent(concep);
					//empl.setConcepto(concept);
					//this.persistencia.cargarObjetoPersistente(concep);
					conceptos.add(concep);
				}*/

				
			 rDTO = ReciboDeSueldoAssembler.getReciboDeSueldoDTO(recb);
	         pm.makePersistent(recb);
	         tx.commit();
	         System.out.println("Recibo dada de alta. OK");
			
		}
		finally
        {
            if (tx.isActive())
            {
                tx.rollback();
            }
            pm.close();
        } 
	return true;
	}

	@Override
	public Vector<ReciboDeSueldoDTO> getRecibo(String cuilEmpleado)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Vector<ReciboDeSueldoDTO> getReciboDeSueldo() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean existeRecibo(String cuilEmpleado) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void eliminarReciboDeSueldo(String cuilEmpleado) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void modificarRecibo(ReciboDeSueldoDTO r) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	public Vector<ClienteDTO> getCliente(String cuit) throws Exception {
        PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
        tx = pm.currentTransaction();
        
        Vector<ClienteDTO> vector = new Vector<ClienteDTO>();
        Collection<Cliente> consultaCol = null;       
        
        try {
            if (!tx.isActive())tx.begin();
            String filter = "cuit == \""+cuit+"\"";
            consultaCol= this.getObjects(pm,Cliente.class,filter);
            Iterator<Cliente> iter = consultaCol.iterator();
            while (iter.hasNext()) {
            	Cliente client = iter.next();
            	ClienteDTO clientDTO = ClienteAssembler.getClienteDTO(client);
            	vector.add(clientDTO);
            }            
            tx.commit();
        } catch (RuntimeException e) {
        	e.printStackTrace();
        } finally {
        	if (tx.isActive()) tx.rollback();
        }
        return vector;
     }
	
	public Vector<ConceptoDTO> getConceptos(Long id ) throws Exception {
        PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
        tx = pm.currentTransaction();
        
        Vector<ConceptoDTO> vector = new Vector<ConceptoDTO>();
        Collection<Concepto> consultaCol = null;       
        try {
            if (!tx.isActive())tx.begin();
            String filter = "ConceptosEmpleadoIdOid == \""+id+"\"";
            consultaCol= this.getObjects(pm,Concepto.class,filter);
            Iterator<Concepto> iter = consultaCol.iterator();
            while (iter.hasNext()) {
            	Concepto con = iter.next();
            	ConceptoDTO conDTO = ConceptoAssembler.getConceptoDTO(con);
            	if (vector.contains((Object)conDTO.getDescripcion())){
            		
            	}else{
            		vector.add(conDTO);
            	}
            }            
            tx.commit();
        } catch (RuntimeException e) {
        	e.printStackTrace();
        } finally {
        	if (tx.isActive()) tx.rollback();
        }
        return vector;
     }
	
	public Collection getObjects(PersistenceManager pm, Class clase,String filter)throws Exception{
		Collection retorno=null;
		try{
			Class empleadoClass = clase;
			Extent clnEmpleado=pm.getExtent(empleadoClass, false); 
			Query query = pm.newQuery(clnEmpleado,filter);
			retorno=(Collection)query.execute();
		} catch(Exception e) {
			throw e;
		}
		return retorno;
	}

	public Object getObject(PersistenceManager pm,Class clase,String filter) throws Exception{
		Object objetoPersistente = null;
		try {

			Extent clnObject = pm.getExtent(clase, true);
			Query query = pm.newQuery(clnObject,filter);
			Collection objetos = (Collection)query.execute();


			Object[] prueba = objetos.toArray();
			if(prueba.length > 0){
				objetoPersistente = prueba[0];
			}	
		}
		catch (Exception ex) {
			ex.printStackTrace();
			throw ex;           
		}
		return objetoPersistente;
	}


}
